<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
//使用类
use App\Http\Controllers\Controller;

class IndexController extends Controller
{




     // 分类数据的处理

    public function checkTypeData($data,$pid=0){

        // 新建数据

        $newArr=array();

        // 获取数据

        foreach ($data as $key => $value) {

            
            if ($value['pid']==$pid) {
                # code...
                $newArr[$value['id']]=$value;
                

                $newArr[$value['id']]['zi']=$this->checkTypeData($data,$value['id']);

            }
        }

        //返回数据

        return $newArr;
    }



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   

        //轮播图
            // if ($slider=\Cache::get('slider')) {
            // # code...
            //     }else{
                    $slider=\DB::table("slider")->where('status','=','0')->orderBy("orders","desc")->get();

                //     \Cache::forever("slider",$slider);
                // }

          
     

        // 查询广告

                    $ads=\DB::table("ads")->where('status',1)->orderBy("sort","desc")->get();


            // 处理左侧数据分类

        $types=\DB::table("types")->get();


                // 递归处理数据
        $type=$this->checkTypeData($types);


            // 处理右侧广告

        foreach ($type as $key => $value) {
            # code...
            $value['rightAds']=\DB::table("typeads")
            ->where("tid",'=',$value['id'])
            ->where('type','=',0)
            ->limit(2)
            ->get();
            $type[$value['id']]['rightAds']= $value['rightAds'];
             // dd($value);
            $value['leftAds']=\DB::table("typeads")
                        ->where("tid",'=',$value['id'])
                        ->where('type','=',1)
                        ->first();
           $type[$value['id']]['leftAds']= $value['leftAds'];
        }
          

            // 处理楼层的商品


        // 遍历一级分类
        foreach ($type as $key => $value) {

            // 新建新的数组

            $newArr=[];
            
            // 遍历二级分类

            foreach ($value['zi'] as $two) {

                // 遍历三级分类

                foreach ($two['zi'] as  $three) {

                    $newArr[]=$three['id'];
                }
            }

            // 查询对应的商品

            $value['goods']=\DB::table("goods")->whereIn("tid",$newArr)->where('is_on_sale',1)->limit(8)->get();
            $type[$value['id']]['goods']= $value['goods'];
        }


        // 明星单品

        $goods=\DB::table("goods")->where('is_on_sale',1)->limit(6)->orderBy("id","desc")->get();

        // 格式化数据
        $data=array(
            "slider"=>$slider,
             "ads"=>$ads,
             "type"=>$type,
             "goods"=>$goods,
             
            );
        // dd($data);
        //加载页面
       return view("home.index")->with($data);
    }

   
}
